<?php

/**
 * Autoloader for MVC components
 * 
 * <p>Rapide_Autoloader_Plugin_MVC automatically loads model, view and controller
 * if class is needed.</p>
 * 
 * <p>Example:
 * <code>$oCustomer = new Model_Customers;</code></p>
 *
 */
class Rapide_Autoloader_Plugin_MVC implements Rapide_Autoloader_Plugin_Interface
{
	/**
	 * Load MVC component for given class name
	 *
	 * @param unknown_type $sClassName
	 * @throws Rapide_Autoloader_Plugin_MVC_Exception if Controller or View does not implement required interfaces
	 * @return boolean true if file has been load or false if has not
	 */
	public function load($sClassName)
	{
		$bLoaded = false;

		if(!$bLoaded && preg_match('/^Controller_/', $sClassName))
		{
			$bLoaded = $this->_loadController($sClassName);
		}

		if(!$bLoaded && preg_match('/^Model_/', $sClassName))
		{
			$bLoaded = $this->_loadModel($sClassName);
		}

		if(!$bLoaded && preg_match('/^View_/', $sClassName))
		{
			$bLoaded = $this->_loadView($sClassName);
		}

		return $bLoaded && class_exists($sClassName);
	}

	private function _loadModel($sClassName)
	{
		$sClassFilePath = _DIR_MODELS . '/' . Rapide_Autoloader::prepareClassFile(substr($sClassName, 6));

		if(!file_exists($sClassFilePath))
		{
			return false;
		}

		require_once $sClassFilePath;

		return true;
	}

	private function _loadView($sClassName)
	{
		$sClassFilePath = _DIR_VIEWS . '/' . Rapide_Autoloader::prepareClassFile(substr($sClassName, 5));

		if(!file_exists($sClassFilePath))
		{
			return false;
		}

		require_once $sClassFilePath;

		$oView = new $sClassName();

		if(!$oView instanceof Rapide_View_Interface)
		{
			$sError = sprintf('View %s does not implement Rapide_View_Interface', $sClassName);
			throw new Rapide_Autoloader_Plugin_MVC_Exception($sError);
		}
		
		return true;
	}

	private function _loadController($sClassName)
	{
		$sClassFileName = substr($sClassName, 11) . Rapide_Autoloader::LIB_EXTENSION;
		$sClassFilePath = _DIR_CONTROLLERS . '/' . $sClassFileName;

		if(!file_exists($sClassFilePath))
		{
			return false;
		}
		
		require_once $sClassFilePath;
		
		$oController = new $sClassName();
		
		if(!$oController instanceof Rapide_Controller_Interface)
		{
			$sError = sprintf('Controller %s does not implement Rapide_Controller_Interface', $sClassName);
			throw new Rapide_Autoloader_Plugin_MVC_Exception($sError);
		}
		
		return true;
	}
}

?>